﻿using Admin2024.Domain.Entity.System;
using Admin2024.Domain.IDomainService.System.IUserService;
using Admin2024.Domain.Interface;
using Admin2024.Domain.ObjValue;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Net.Sockets;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace Admin2024.Domain.DomainService.System.UserService
{
    public class JwtService : IJwtService
    {
        private readonly JwtSettings jwtSettings;

        private readonly IRepository<AppUser> UserRep;
        public JwtService(JwtSettings jwtSettings, IRepository<AppUser> UserRep)
        {
            this.jwtSettings = jwtSettings;
            this.UserRep = UserRep;
        }
        //生成token
        //public string GenerateToken(AppUser user)
        //{
        //    var tokenHandler = new JwtSecurityTokenHandler(); //创建一个实例（工具箱）用来生成 解析 和验证 Token

        //    string secretKey = jwtSettings.SecretKey ?? "Jkf32&*D9!Gt4uQ%2jwwfag12gwadawdgwegawg23232f"; // 如果 SecretKey 为空，则使用默认值
        //    var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey));
        //    var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
        //    var tokenDescriptor = new SecurityTokenDescriptor // 定义令牌描述符
        //    {
        //        Subject = new ClaimsIdentity(new[]
        //        {
        //              new Claim(ClaimTypes.Name, user.Username),
        //             new Claim("Id", user.Id.ToString())
        //}),
        //        IssuedAt = DateTime.UtcNow, //设置令牌生成时间
        //        NotBefore = DateTime.UtcNow.AddMinutes(jwtSettings.ExpirationMinutes - 5),//设置生效时间
        //        Expires = DateTime.UtcNow.AddMinutes(jwtSettings.ExpirationMinutes), // 设置过期时间
        //        Issuer = jwtSettings.Issuer, // 设置发行者
        //        Audience = jwtSettings.Audience, // 设置受众
        //        SigningCredentials = creds,
        //    };

        //    SecurityToken token = tokenHandler.CreateToken(tokenDescriptor);
        //    return tokenHandler.WriteToken(token);
        //}
        public string GenerateToken(AppUser user,string rolename)
        {
            var tokenHandler = new JwtSecurityTokenHandler();

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.SecretKey));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new[]
                {
                new Claim(ClaimTypes.Name, user.Username),
                new Claim("Id", user.Id.ToString()),
                new Claim("RoleName",rolename)
            }),
                IssuedAt = DateTime.UtcNow,
                NotBefore = DateTime.UtcNow.AddMinutes(-5), // 设置生效时间为当前时间减去5分钟
                Expires = DateTime.UtcNow.AddMinutes(jwtSettings.ExpirationMinutes),
                Issuer = jwtSettings.Issuer,
                Audience = jwtSettings.Audience,
                SigningCredentials = creds,
            };

            SecurityToken token = tokenHandler.CreateToken(tokenDescriptor);
            
            return tokenHandler.WriteToken(token);
        }

        // 解析 JWT
        public JwtSecurityToken ValidateToken(string token)
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            JwtSecurityToken jwt =  tokenHandler.ReadJwtToken(token);
            return jwt;

        }

        public async Task<AppUser> GetUserIdFromToken(string token)
        {
             var to = ValidateToken(token);

            var userId = to.Claims.First(item => item.Type == "Id").Value;

            var user = await UserRep.GetByIdAsync(Guid.Parse(userId));
            return user;
        }
    }
}
